/**
 * Project Name:fire-industry-DM-center
 * File Name:ProjectStaticServiceImpl.java
 * Package Name:com.firestone.service.company.impl
 * Date:2018年4月17日下午2:23:54
 *
*/

package com.firestone.service.company.impl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ScrolledPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import com.firestone.bean.entity.elasticsearch.im.DmImProject;
import com.firestone.bean.entity.elasticsearch.im.DmImProjectStatic;
import com.firestone.core.constants.ConstantDmImProjectKey;
import com.firestone.core.constants.ConstantDmImProjectStaticKey;
import com.firestone.core.constants.ConstantKey;
import com.firestone.dao.repository.DmImProjectStaticRepository;
import com.firestone.service.company.IProjectStaticService;
import com.firestone.service.patent.IPatentService;

/**
 * @Description: TODO(企业统计表业务层实现类)
 * @author CAIYJ
 * @date 2018年4月17日 下午2:23:54
 */
@Service
public class ProjectStaticServiceImpl implements IProjectStaticService {

    private static final Logger loggger = LogManager
            .getLogger(ProjectStaticServiceImpl.class);

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @Autowired
    private DmImProjectStaticRepository imProjectStaticRepository;

    @Autowired
    private IPatentService patentService;

    @Override
    public void pushData() throws Exception {
        SearchQuery searchQuery = new NativeSearchQuery(
                QueryBuilders.matchAllQuery());
        searchQuery
                .setPageable(PageRequest.of(ConstantKey.ES_DEFAULT_SCROLL_PAGE,
                        ConstantKey.ES_DEFAULT_SCROLL_SIZE));
        searchQuery.addFields(ConstantDmImProjectKey.address,
                ConstantDmImProjectKey.address_area,
                ConstantDmImProjectKey.address_city,
                ConstantDmImProjectKey.address_country,
                ConstantDmImProjectKey.category,
                ConstantDmImProjectKey.chengliriqi,
                ConstantDmImProjectKey.ismedical,
                ConstantDmImProjectKey.jingyingzhuangtai,
                ConstantDmImProjectKey.name, ConstantDmImProjectKey.type,
                ConstantDmImProjectKey.zhucehao,
                ConstantDmImProjectKey.zhuceziben_base,
                ConstantDmImProjectKey.zhuceziben_currency,
                ConstantDmImProjectKey.zhuceziben_num,
                ConstantDmImProjectKey.ID);
        ScrolledPage<DmImProject> scroll = (ScrolledPage<DmImProject>) elasticsearchOperations
                .startScroll(ConstantKey.ES_DEFAULT_SCROLL_TIME_IN_MILLIS,
                        searchQuery, DmImProject.class);
        Set<String> ids = null;
        List<DmImProjectStatic> list = null;
        DmImProjectStatic projectStatic = null;
        while (scroll.hasContent()) {
            ids = new HashSet<>();
            list = new ArrayList<>();
            for (DmImProject project : scroll.getContent()) {
                ids.add(project.getId());
                projectStatic = new DmImProjectStatic();
                projectStatic.setProject_id(project.getId());
                BeanUtils.copyProperties(project, projectStatic);
            }
            list.add(projectStatic);
            Future<Map<String, Long>> patent = patentService
                    .projectPatentNum(list, ids);
            projectStaticTrans(list, patent.get(),
                    ConstantDmImProjectStaticKey.patentnum);
            imProjectStaticRepository.saveAll(list);
            scroll = (ScrolledPage<DmImProject>) elasticsearchOperations
                    .continueScroll(scroll.getScrollId(),
                            ConstantKey.ES_DEFAULT_SCROLL_TIME_IN_MILLIS,
                            DmImProject.class);
        }
    }

    /**
     * @Description: TODO(统计bean的数据转换，针对各个维度的数量)
     * @param list
     * @param aggs
     * @param field
     * @author CAIYJ
     * @date 2018年4月18日 上午11:01:09
     * @lastModifier CAIYJ
     */
    private void projectStaticTrans(List<DmImProjectStatic> list,
            Map<String, Long> aggs, String field) {
        if (aggs != null && aggs.size() > 0 && null != list && list.size() > 0
                && null != field) {
            for (DmImProjectStatic project : list) {
                Field f = null;
                try {
                    f = DmImProjectStatic.class.getDeclaredField(field);
                } catch (NoSuchFieldException e) {
                    return;
                } catch (SecurityException e) {
                    loggger.error("projectStaticTrans--" + field
                            + "--SecurityException", e);
                }
                f.setAccessible(true);
                try {
                    f.set(project, aggs.get(project.getId()) != null
                            ? aggs.get(project.getId()).intValue() : 0);
                } catch (IllegalArgumentException e) {
                    loggger.error("projectStaticTrans--" + field
                            + "--IllegalArgumentException", e);
                } catch (IllegalAccessException e) {
                    loggger.error("projectStaticTrans--" + field
                            + "--IllegalAccessException", e);
                }
            }
        }
    }
}
